package com.boot.dog.rest.core;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.boot.dog.common.annotation.SysLog;
import com.boot.dog.common.constant.Const;
import com.boot.dog.common.enums.EnumConst;
import com.boot.dog.common.util.*;
import com.boot.dog.entities.vo.EnumVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: MaxLv
 * @Date: 2019/12/2
 */
@RestController
@RequestMapping("/core/common")
@RequiredArgsConstructor
public class CommonRest {

    @Value("${dog.temp.server.url}")
    private String tempServerUrl;

    @GetMapping("/validateCode")
    @ApiOperation(value = "获取验证码")
    @SneakyThrows
    public void validateCode(HttpServletRequest request, HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(130, 36, 4, 4);
        request.getSession().setAttribute("code", lineCaptcha.getCode());
        response.setContentType("image/png");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        lineCaptcha.write(response.getOutputStream());
    }

    @GetMapping("/getEnum/{type}")
    @ApiOperation(value = "获取枚举列表")
    @SneakyThrows
    public ApiResult<List<EnumVo>> getEnum(@PathVariable String type) {
        Method method = Class.forName(Const.ENUMS_PACKAGE_NAME + type).getMethod("values");
        EnumConst[] enumConsts = (EnumConst[]) method.invoke(null);
        List<EnumVo> vos = Arrays.stream(enumConsts).map(enumConst ->
                new EnumVo(enumConst.code(), enumConst.text())
        ).collect(Collectors.toList());
        return Result.of(vos);
    }

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传图片")
    @SysLog(desc = "图片上传")
    @SneakyThrows
    public ApiResult<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        DogMultipartFile multipartFile = new DogMultipartFile(file.getOriginalFilename(), file.getInputStream(),
                file.getSize());
        String ret = FileStoreUtil.saveImgToTemp(multipartFile);
        Map<String, String> map = new HashMap<>(2);
        map.put("filename", ret);
        map.put("url", CommonUtil.concatUrl(tempServerUrl, ret));
        return Result.of(map);
    }

}
